package com.ljc.cjgl.controller.bbs;

import com.ljc.cjgl.custom.TablePageable;
import com.ljc.cjgl.entitiy.bbs.Article;
import com.ljc.cjgl.service.bbs.ArticleService;
import org.abyss.data.specifications.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashSet;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: JavaJun
 * Date: 2019-04-28 9:04
 */
@Controller
@RequestMapping(value = "/bbs")
public class BbsHelloController {

    @Autowired
    private ArticleService articleService;

    @GetMapping(value = "")
    public String index(ModelMap map, Integer pageNo, String search, Integer courseId) {

        TablePageable pageable = new TablePageable();
        pageable.setLimit(10);

        if (pageNo == null || pageNo <= 0 ) {
            pageable.setOffset(0);
        } else {
            pageable.setOffset((pageNo - 1) * pageable.getLimit());
        }
        /* 根据id进行逆序排序，这个样子后发布的帖子总是显示在前面 */
        pageable.setSort("id");
        pageable.setOrder("desc");

        PageRequest pageRequest = pageable.bulidPageRequest();
        HashSet<Rule> rules=new HashSet<>();
        if(StringUtils.hasText(search)) {
            HashSet<Rule> rules2=new HashSet<>();
            rules2.add(Rule.property("title").contain(search));
            rules2.add(Rule.property("sysUser.name").contain(search));
            rules.add(Rule.or(rules2));
        }
        if(courseId != null) {
            HashSet<Rule> rules2=new HashSet<>();
            rules2.add(Rule.property("course.id").equal(courseId));
            rules.add(Rule.or(rules2));
        }
        Specification<Article> specification = Rule.and(rules).toSpecification();
        Page<Article> page=articleService.findAll(specification, pageRequest);
        long totals = page.getTotalElements();
        int totalPages = page.getTotalPages();
        map.put("totalPages", totalPages);
        // 当前页
        int nowPageNumber = page.getNumber() + 1;
        map.put("nowPageNumber", nowPageNumber);
        // 下一页
        int downPageNumber = nowPageNumber + 1;
        map.put("downPageNumber", downPageNumber);
        // 上一页
        int upPageNumber = nowPageNumber - 1;
        map.put("upPageNumber", upPageNumber);
        List<Article> contentList = page.getContent();
        map.put("totals", totals);
        map.put("contentList", contentList);
        return "bbs/home";
    }

}
